#include "DataSender.h"
#include <QDebug>
#include <QMutexLocker>
#include <QThread>

DataSender::DataSender(int width, int height, int fps, QObject *parent)
    : QObject(parent), m_destPort(0)
{
    m_width = width;
    m_height = height;
    m_fps = fps;
}

void DataSender::setDestination(const QString &ip, quint16 port)
{
    QMutexLocker locker(&m_mutex);
    m_destAddress.setAddress(ip);
    m_destPort = port;
}

void DataSender::setDestination(const QHostAddress &address, quint16 port)
{
    QMutexLocker locker(&m_mutex);
    m_destAddress = address;
    m_destPort = port;
}

void DataSender::setBindIpAndPort(const QString &ip, quint16 port)
{
    //QMutexLocker locker(&m_mutex);
    m_bindIP = ip;
    m_bindPort = port;
}

void DataSender::onSendData(const QByteArray &data)
{
    qDebug() << "发送数据data:" << data.size();
    QMutexLocker locker(&m_mutex);

    if (m_destPort == 0 || m_destAddress.isNull()) {
        emit errorOccurred("未设置目标地址和端口");
        return;
    }

    if (data.isEmpty()) {
        return; //忽略空数据
    }

    qDebug() << "准备发送数据，总大小:" << data.size() << "字节";


    // 分片大小设置（根据需求调整，通常不超过MTU，建议1024-4096字节）
    const int fragmentSize = 1400;
    int totalFragments = (data.size() + fragmentSize - 1) / fragmentSize;
    int currentFragment = 0;

    qDebug() << "数据将分为" << totalFragments << "个分片发送";

    // 循环发送所有分片
    while (currentFragment < totalFragments) {
        // 计算当前分片的偏移量和大小
        int startPos = currentFragment * fragmentSize;
        int endPos = qMin(startPos + fragmentSize, data.size());
        int currentSize = endPos - startPos;

        // 提取当前分片数据
        QByteArray fragment = data.mid(startPos, currentSize);

        // 发送分片
        qint64 bytesSent = m_socket->writeDatagram(
            fragment,
            m_destAddress,
            m_destPort
        );

        // 检查发送结果
        if (bytesSent != currentSize) {
            emit errorOccurred(
                QString("分片 %1/%2 发送失败: %3")
                .arg(currentFragment + 1)
                .arg(totalFragments)
                .arg(m_socket->errorString())
            );
        } else {
            qDebug() << "分片" << currentFragment + 1 << "/" << totalFragments
                     << "发送成功，大小:" << currentSize << "字节";
        }

        currentFragment++;

        emit sigToShowUi(m_width, m_height, m_fps);  //发送至ui显示

        // 可选：添加微小延迟，避免网络拥塞
        QThread::msleep(1);
    }
}

void DataSender::onInitUdp()
{
    m_socket = new QUdpSocket(this);
    m_socket->bind(QHostAddress(m_bindIP), m_bindPort);
}
